#nullable enable
using Microsoft.AspNetCore.Components;
using Application.Service.LogCache;
using System.Diagnostics.CodeAnalysis;
using Application.Core.Entity;
using Application.Core.Dto;
using BootstrapBlazor.Components;
using System.Linq;
using SqlSugar;
using Application.Web.Core.Services;

namespace Application.Web.Entry.Pages
{
    /// <summary>
    /// 
    /// </summary>
    public partial class SystemLogs : ComponentBase
    {
        [Inject] public SystemLogService SystemLogService { get; set; } = default!;
        [Inject] public CheckPermission CheckPermission { get; set; } = default!;
        [Inject] public NavigationManager Navigation { get; set; } = default!;

        [NotNull]
        private List<SystemLog>? Items { get; set; }

        private IEnumerable<SelectedItem>? SearchItems { get; set; }

        private static IEnumerable<int> PageItemsSource => new[] { 10, 20,30,40 };

        private bool _hasPermission = false;
        private bool _isReadOnly = false;

        /// <summary>
        /// OnInitializedAsync 方法
        /// </summary>
        protected override async Task OnInitializedAsync()
		{
			// 检查页面访问权限
            _hasPermission = await CheckPermission.CanAccessPageAsync("log");
            
            if (!_hasPermission)
            {
                CheckPermission.RedirectToNoPermission();
                return;
            }

            // 检查是否为只读权限
            _isReadOnly = await CheckPermission.IsPageReadOnlyAsync("log");

			await base.OnInitializedAsync();
			
			if (SearchItems!=null && SearchItems.Any())
			{
				return;
			}
			var levels = SystemLogService.GetLogLevels();
			var searchItems = new List<SelectedItem>()
			{
				new()
				{
					Text = "请选择 ...",
					Value = ""
				}
			};
			foreach (var item in levels)
			{
				searchItems.Add(new()
				{
					Text = item,
					Value = item
				});

			}
			SearchItems = searchItems.AsEnumerable();
		}


		/// <summary>
		/// 查询操作方法
		/// </summary>
		/// <param name="options"></param>
		/// <returns></returns>
		private async Task<QueryData<SystemLog>> OnQueryAsync(QueryPageOptions options)
        {
            // 每次查询都重新从数据库获取最新数据
            Items = (await SystemLogService.GetAllEntiyAsync()).ToList();
            
            // 应用筛选条件
            Items = Items.AsQueryable().Where(options.ToFilterFunc<SystemLog>()).OrderByDescending(opt=>opt.CreateTime).ToList();
            
            // 排序
            var isSorted = false;
            if (!string.IsNullOrEmpty(options.SortName))
            {
                Items = Items.AsQueryable().Sort(options.SortName, options.SortOrder).ToList();
                isSorted = true;
            }

            var total = Items.Count();
            var result = new QueryData<SystemLog>()
            {
                Items = Items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList(),
                TotalCount = total,
                IsFiltered = true,
                IsSorted = isSorted,
                IsSearch = true
            };
            return result;
        }

        /// <summary>
        /// 导航到首页
        /// </summary>
        private void GoToHome()
        {
            Navigation.NavigateTo("/");
        }
    }
}